﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using MyLocalChurch.Models;
using log4net;
using log4net.Config;

namespace MyLocalChurch
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            XmlConfigurator.Configure();
            Database.SetInitializer(new MyDbInitializer());
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            if (exception == null)
                return;

            var logger = LogManager.GetLogger(typeof(_Default));

            logger.Error(exception.Message, exception);

            if (exception is DbEntityValidationException)
            {
                var valEx = (DbEntityValidationException) exception;

                foreach (var eve in valEx.EntityValidationErrors)
                {
                    logger.Error(string.Format(
                        "Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State));

                    foreach (var ve in eve.ValidationErrors)
                    {
                        logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                   ve.PropertyName, ve.ErrorMessage));
                    }
                }
            }
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
